import React, { useState, useEffect } from 'react';
import { useParams, useNavigate, Link } from 'react-router-dom';
import ReactMarkdown from 'react-markdown';
import remarkGfm from 'remark-gfm';
import rehypeHighlight from 'rehype-highlight';
import { Article } from '@/interfaces/article';
import { formatDistanceToNow } from 'date-fns';
import BackButton from '@/components/common/BackButton';
import ShareButton from '@/components/common/ShareButton';
import RelatedArticles from '@/components/common/RelatedArticles';

const mockArticle: Article = {
  id: '1',
  title: 'Getting Started with React 18: A Complete Guide',
  content: `
# Introduction

React 18 introduces several groundbreaking features that revolutionize how we build user interfaces. This comprehensive guide will walk you through everything you need to know about the latest version of React.

## Concurrent Features

The most significant addition in React 18 is the introduction of concurrent features. These features allow React to work on multiple state updates simultaneously, making your applications more responsive and performant.

### Automatic Batching

React 18 automatically batches state updates, even those inside promises, timeouts, and native event handlers. This means fewer re-renders and better performance out of the box.

\`\`\`jsx
// Before React 18 - triggers two re-renders
function handleClick() {
  setCount(c => c + 1);
  setFlag(f => !f);
}

// React 18 - automatically batched into one re-render
function handleClick() {
  setCount(c => c + 1);
  setFlag(f => !f);
}
\`\`\`

### Suspense Improvements

Suspense has been enhanced to support more use cases, including server-side rendering and data fetching patterns.

## New Hooks

React 18 introduces several new hooks that make concurrent features easier to use:

- **useId**: For generating unique IDs
- **useDeferredValue**: For deferring non-urgent updates
- **useTransition**: For marking state updates as transitions

## Migration Guide

Upgrading to React 18 is straightforward for most applications. Here's what you need to know:

1. Update your packages
2. Update your root API
3. Test concurrent features gradually

## Conclusion

React 18 represents a major step forward in React's evolution. The concurrent features, improved Suspense, and new hooks provide developers with powerful tools to build better user experiences.

Start experimenting with these features in your projects and see how they can improve your application's performance and user experience.
  `,
  excerpt: 'Learn the new features and improvements in React 18, including concurrent rendering and automatic batching.',
  author: 'John Doe',
  publishDate: '2024-01-15',
  lastModified: '2024-01-16',
  tags: ['React', 'JavaScript', 'Frontend'],
  category: 'Development',
  readTime: 5,
  status: 'published',
  coverImage: 'https://via.placeholder.com/800x400'
};

const ArticleDetail: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const [article, setArticle] = useState<Article | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    // Simulate API call
    setTimeout(() => {
      setArticle(mockArticle);
      setLoading(false);
    }, 500);
  }, [id]);

  if (loading) {
    return (
      <div className="min-h-screen bg-white dark:bg-ios-gray-900 flex items-center justify-center">
        <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-ios-blue"></div>
      </div>
    );
  }

  if (!article) {
    return (
      <div className="min-h-screen bg-white dark:bg-ios-gray-900 flex items-center justify-center">
        <div className="text-center">
          <h1 className="text-2xl font-bold text-ios-gray-900 dark:text-white mb-4">
            Article Not Found
          </h1>
          <button
            onClick={() => navigate('/')}
            className="text-ios-blue hover:text-ios-blue/80 transition-colors"
          >
            Back to Home
          </button>
        </div>
      </div>
    );
  }

  const formattedDate = formatDistanceToNow(new Date(article.publishDate), { addSuffix: true });

  return (
    <div className="min-h-screen bg-white dark:bg-ios-gray-900">
      {/* Header */}
      <header className="sticky top-0 z-50 bg-white/80 dark:bg-ios-gray-900/80 backdrop-blur-apple border-b border-ios-gray-200 dark:border-ios-gray-700">
        <div className="max-w-4xl mx-auto px-4 py-4">
          <div className="flex items-center justify-between">
            <BackButton onClick={() => navigate('/')} />
            <div className="flex items-center space-x-3">
              <Link
                to="/settings"
                className="p-2 text-ios-gray-600 dark:text-ios-gray-400 hover:text-ios-blue transition-colors"
                title="Settings"
              >
                <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.065 2.572c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.572 1.065c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.065-2.572c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z" />
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" />
                </svg>
              </Link>
              <ShareButton article={article} />
            </div>
          </div>
        </div>
      </header>

      {/* Hero Section */}
      <section className="relative">
        {article.coverImage && (
          <div className="h-80 md:h-96 overflow-hidden">
            <img 
              src={article.coverImage} 
              alt={article.title}
              className="w-full h-full object-cover"
            />
            <div className="absolute inset-0 bg-gradient-to-t from-black/50 to-transparent"></div>
          </div>
        )}
        
        <div className="max-w-4xl mx-auto px-4 py-8">
          {/* Category & Read Time */}
          <div className="flex items-center space-x-2 mb-4">
            <span className="inline-flex items-center px-3 py-1 rounded-apple-sm text-sm font-medium bg-ios-blue/10 text-ios-blue">
              {article.category}
            </span>
            <span className="text-ios-gray-500 dark:text-ios-gray-400 text-sm">
              {article.readTime} min read
            </span>
          </div>

          {/* Title */}
          <h1 className="text-3xl md:text-4xl font-bold text-ios-gray-900 dark:text-white mb-4 leading-tight">
            {article.title}
          </h1>

          {/* Meta Information */}
          <div className="flex items-center space-x-4 mb-6">
            <div className="flex items-center space-x-2">
              <div className="w-10 h-10 rounded-full bg-ios-gray-300 dark:bg-ios-gray-600"></div>
              <div>
                <p className="text-ios-gray-900 dark:text-white font-medium">
                  {article.author}
                </p>
                <p className="text-ios-gray-500 dark:text-ios-gray-400 text-sm">
                  {formattedDate}
                </p>
              </div>
            </div>
          </div>

          {/* Tags */}
          <div className="flex flex-wrap gap-2 mb-8">
            {article.tags.map((tag) => (
              <span 
                key={tag}
                className="inline-flex items-center px-3 py-1 rounded-apple-sm text-sm bg-ios-gray-100 dark:bg-ios-gray-700 text-ios-gray-700 dark:text-ios-gray-300"
              >
                #{tag}
              </span>
            ))}
          </div>
        </div>
      </section>

      {/* Article Content */}
      <main className="max-w-4xl mx-auto px-4 pb-12">
        <article className="prose prose-lg max-w-none dark:prose-invert prose-headings:text-ios-gray-900 dark:prose-headings:text-white prose-p:text-ios-gray-700 dark:prose-p:text-ios-gray-300 prose-a:text-ios-blue prose-code:text-ios-blue prose-pre:bg-ios-gray-50 dark:prose-pre:bg-ios-gray-800">
          <ReactMarkdown
            remarkPlugins={[remarkGfm]}
            rehypePlugins={[rehypeHighlight]}
            className="article-content"
          >
            {article.content}
          </ReactMarkdown>
        </article>
      </main>

      {/* Related Articles */}
      <RelatedArticles currentArticleId={article.id} />
    </div>
  );
};

export default ArticleDetail;